package com.dz.core.util;

import com.alibaba.fastjson.JSON;
import com.dz.core.component.exception.DzException;
import com.dz.core.constant.ResCode;
import com.dz.core.dto.ResBody;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 渲染工具类
 *
 * @author fengshuonan
 * @date 2017-08-25 14:13
 */
public class RenderUtil {


    /**
     * 渲染响应数据为 ResBody
     */
    public static void renderToResBody(HttpServletResponse response, ResCode code){
        PrintWriter writer = null;
        try {
            response.setContentType("application/json;charset=utf-8");
            response.setCharacterEncoding("UTF-8");
            writer = response.getWriter();
            ResBody body = new ResBody(code);
            writer.write(JSON.toJSONString(body));
        } catch (IOException e) {
            throw new DzException(ResCode.SERVER_ERROR,e.getMessage());
        } finally {
            writer.flush();
            writer.close();
        }

    }
}
